<?php
global $m, $tab, $a;


$df = $AppUI->getPref('SHDATEFORMAT');

$perm = &$AppUI->acl();
if (!$perm->userHasRole($AppUI->user_id, 'Marketing')) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect("m=home&tab=0");
	exit;
}

$beingProcess = dPgetParam($_POST, 'beingProcess', 0);
if ($beingProcess) {
	include(DP_BASE_DIR."/modules/projects/do_many_projects_process.php");
	return;
}
require_once($AppUI->getModuleClass('projects'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once($AppUI->getMasterDataClass('mdstatus'));
require_once($AppUI->getMasterDataClass('mdcurrency'));
if (isset($_POST['resetAction'])) {
	$_POST = $AppUI->getPOST('PROCESS_POST');
	$canProcess = $_POST['canProcessAction'];
	$AppUI->unsetPOST('PROCESS_POST');
	if ($canProcess) {
		$_POST['canProcessAction'] = 'Can Process';
	}
}
else {
	if (count($_POST) > 0) {
		$AppUI->savePOST('PROCESS_POST');
	}
	else {
		$_POST = $AppUI->getPOST('PROCESS_POST');
	}
}
$AppUI->savePlace();

$page_offset = intval( dPgetParam( $_GET, 'page_offset', 0 ) );
//get post params
$canProcess = isset($_POST['canProcessAction']);
$page_limit = intval( dPgetParam( $_POST, 'page_limit', 10));
$customer = intval( dPgetParam( $_POST, 'project_company', 0 ) );
$task_status = dPgetParam( $_POST, 'task_status', array());
$item_be_check = intval( dPgetParam( $_POST, 'item_be_check', 0 ) );
$keyword = dPgetParam( $_POST, 'keyword', '' );
$from_date = dPgetParam( $_POST, 'complete_from_date', null );
$to_date = dPgetParam( $_POST, 'complete_to_date', null );

//0913.171.014
if ($canProcess) {
	$complete_status = new CMDStatus();
	$project_completed = dPgetSysVal( 'ProjectCompleted' );
	$complete_status->loadByCode($project_completed[0]);
	$status_id = $complete_status->status_id;
}

$objMD = new CCompany();
$cusList = $objMD->getAllowedRecords($AppUI->user_id, 'company_id, company_name', 'company_name');
$cusList = arrayMerge(array('0'=>"" . $AppUI->_(''). ""), $cusList);

$objMD = new CMdStatus();
$statList = NULL;
$statList = $objMD->getStatusList('Reference');

//do search
$q = new DBQuery();
$q->dropTemp('pitems');
$q->exec();
$q->clear();

$q->createTemp('pitems');
$q->addTable('items');
if ($item_type > 0) {
	$q->addWhere("item_type1 = $item_type");
}
$q->exec();
$q->clear();

//main query for tasks
$q->addTable('tasks');
$q->innerJoin('projects', 'pro', 'project_id = task_project');
$q->innerJoin('pitems', 'pi', 'item_id = task_item');
$q->leftJoin('md_unit', 'u', 'tasks.task_unit = u.unit_id');
$q->leftJoin('quotations', 'q', 'quote_id = task_quotation ');
if ($status_id > 0) {
	$q->addWhere("project_rstatus  = $status_id");
} else if (!$canProcess) {
	$processed_status = new CMDStatus();
	$project_processed = dPgetSysVal( 'ProjectProcessed' );
	$processed_status->loadByCode($project_processed[0]);
	$q->addWhere("project_rstatus  != " . $processed_status->status_id);
}
if ($project_name != '') {
	$q->addWhere("project_name LIKE '%$project_name%'");
}
if ($project_code != '') {
	$q->addWhere("project_code LIKE '%$project_code%'");
}
if ($keyword != '') {
	$q->addWhere("(project_code LIKE '%$keyword%' or project_name LIKE '%$keyword%')");
}
if ($from_date != '') {
	$q->addWhere("pro.project_actual_end_date  >= $from_date");
	$from_date = new CDate($from_date);
}
if ($to_date != '') {
	$q->addWhere("pro.project_actual_end_date  <= $to_date");
	$to_date = new CDate($to_date);
}
if ($customer > 0) {
	$q->addWhere("pro.project_company  = $customer");
}

$tmp = array();
if (in_array(1, $task_status)) {//not link with quotation
	$tmp []= '(task_quotation IS NULL or task_quotation = 0)';
}
if (in_array(2, $task_status)) {//broken quotation
	$tmp []= '(task_quotation_version > 0 && (task_quotation_version < quote_version OR quote_completed = 0))';
}
if (in_array(3, $task_status)) {//to be check
	$tmp []= '(pi.item_be_check = 1)';
}
if (count($tmp) > 0) {
	$q->addWhere("(" . implode(" OR ", $tmp) . ")");
}

$q->addOrder('task_project, task_start_date desc, task_name');
$q->setLimit($page_limit, $page_offset);
$qTotal = $q->prepare();
$q->addQuery('distinct tasks.*, pro.*, q.*, pi.*, u.unit_name');
$tasks = $q->loadList();

$q = new DBQuery();
$q->dropTemp('pitems');

$curArr = getCurrencyList();
?>
<form name="checkFrm" action="?m=<?=$m?>&tab=<?=$tab?>" method="post">
<table cellspacing="0" cellpadding="0" border="0" width="100%" class="infopanel">
<tr><td width="50%">
<table cellspacing="0" cellpadding="4" border="0" width="100%" >
<tr>
	<td align="right" width="100px"><?=$AppUI->_('From date')?></td>
	<td nowrap="nowrap" width="100px">
		<input id="idDateFrom" type="hidden" name="complete_from_date"
				value="<?=$from_date ? $from_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateFromD" type="text" style="width: 80px"
				value="<?=$from_date ? $from_date->format( $df ) : ''?>"
				class="text" disabled="disabled" />
		<img id="idDateFromB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
	<td align="right" width="80px"> <?=$AppUI->_('To date')?></td>
	<td nowrap="nowrap">
		<input id="idDateTo" type="hidden" name="complete_to_date"
				value="<?=$to_date ? $to_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateToD" type="text" style="width: 80px"
				value="<?=$to_date ? $to_date->format( $df ) : ''?>"
				class="text" disabled="disabled" />
		<img id="idDateToB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Task')?></td>
	<td colspan="100%">
		<input type="checkbox" name="task_status[]" value="1" <?=in_array(1, $task_status) ? "checked" : ""?>>Not link</input>
		<input type="checkbox" name="task_status[]" value="2" <?=in_array(2, $task_status) ? "checked" : ""?>>Broken link</input>
		<input type="checkbox" name="task_status[]" value="3" <?=in_array(3, $task_status) ? "checked" : ""?>>To be checked</input>
	</td>
</tr>
</table>
</td>
<td valign="top">
<table cellspacing="0" cellpadding="4" border="0" width="50%">
	<tr>
		<td align="right" nowrap><?=$AppUI->_("Reference code")?></td>
		<td>
			<input type="text" name="keyword" value="<?=@$keyword?>" style="width: 200px"/>
		</td>
	</tr>
	<tr>
		<td align="right"><?=$AppUI->_('Customer')?></td>
		<td colspan="100%"><?= arraySelect($cusList, 'project_company', ' id="customer" size="1" class="text" style="width: 208px;"', $customer, true)?></td>
	</tr>
</table>
</tr></td>
</table>
<table cellspacing="0" cellpadding="6" border="0" width="100%" class="subinfopanel">
<tr>
	<td>
		<input class="button" type="submit" name="searchAction" value="<?=$AppUI->_('Search');?>"/>
		<input class="button" type="submit" name="canProcessAction" value="<?=$AppUI->_('Can process');?>"/>
		<input class="button" type="submit" name="resetAction" value="<?=$AppUI->_('reset');?>"/>
	</td>
</tr>
</table>
</form>
<form name="processFrm" id="processFrm" action="?m=<?=$m?>&tab=<?=$tab?>" method="POST">
<input type="hidden" name="beingProcess" value="0"/>
<table id="idReferenceList" class="list" cellspacing="0" cellpadding="2" border="0" width="100%">
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
			<?php if ($canProcess):?>
			<th align="center"><input type="checkbox" id="checkAllProcess" name="checkAllProcess" value="1" onclick="checkAllCbProcess(this.form, this.checked)"/></th>
			<?php endif;?>
			<th><?=$AppUI->_('Code')?></th>
			<th ><?=$AppUI->_('Name')?></th>
			<th><?=$AppUI->_('Quotation')?></th>
			<th><?=$AppUI->_('Sales amount')?></th>
			<th><?=$AppUI->_('Start date')?></th>
			<th><?=$AppUI->_('End date')?></th>
			<!--<th><$AppUI->_('Remarks')?></th>-->
		</tr>
<?php
if (is_array($tasks) && count($tasks) > 0) {
	$totalRows = 0;
	$qTotal = str_ireplace('select *', 'select count(*) as total_rows', $qTotal);
	$tmp = db_loadList($qTotal);
	$totalRows = $tmp[0]['total_rows'];

	require_once($AppUI->getLibraryClass('codeigniter/pagination'));
	$pagination = new CI_Pagination();
	$config = array(
		'base_url' => '?m=projects&tab=1',
		'total_rows' => $totalRows,
		'per_page' => $page_limit

	);
	$pagination->initialize($config);
	?>

	<script type="text/javascript">
		function submitForm(offset) {
			document.reportFrm.offset.value = offset;
			document.reportFrm.submit();
		}
	</script>
	<?
	$i = 1;
	$lastProject = 0;
	foreach ($tasks as $row) {
		$my_cc_task = $needCheckCostCenter ? $row['task_costcenter'] == $AppUI->user_costcenter : TRUE;
		$i++;
		$start_date = new CDate($row['task_start_date']);
		$end_date = new CDate($row['task_end_date']);
		if ($lastProject != $row['task_project']) {
			$referenceURL = "?m=projects&a=view&project_id=" . $row['task_project'];
	?>
				<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
					<?php if ($canProcess):?>
					<td align="center"><input type="checkbox" name="checkProcess[]" value="<?=$row['project_id']?>"/></td>
					<?php endif;?>
					<td colspan="3">
						<a href="<?=$referenceURL?>" style="border: 1px outset rgb(238, 238, 238); background-color: rgb(255, 255, 255); padding: 3px;"><b><?=$row['project_name']?></b></a>
					</td>
					<td>
						<?=$curArr[$row['project_currency']]?>
					</td>
					<td colspan="100%">&nbsp;</td>
				</tr>
	<?php
			$lastProject = $row['task_project'];
			$i++;
		}
		?>
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>" >
			<?php if ($canProcess):?>
			<td>&nbsp;</td>
			<?php endif;?>
			<td onClick="showTask(<?=$row['task_id']?>)"><?=$row['item_code']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" nowrap="nowrap">
				<div style='float:left'><?=$row['task_name']?></div>
				<div style='float:right'><?=$row['item_be_check'] == 1 ? dPshowImage("images/red.png") : ""?></div>
			</td>
			<td onClick="showTask(<?=$row['task_id']?>)" nowrap="nowrap">
				<div style='float:left'><?=$row['quote_name']?></div>
				<div style='float:right'>
					<?php
						if (intval($row['task_quotation']) > 0) {
							if (in_array(2, $task_status) && ($row['task_quotation_version'] < $row['quote_version'] || $row['quote_completed'] < 1)) {
								echo dPshowImage("images/red.png");
							}
						} else if (in_array(1, $task_status)){
							echo dPshowImage("images/red.png");
						}
					?>
			</td>
			<td onClick="showTask(<?=$row['task_id']?>)" nowrap="nowrap" align="right"><?=currencyFormat($row['task_fee'], $row['project_currency'] == CURRENCY_VND_VALUE)?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" >
				<div style="float:left"><?=$start_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_start_time']?></div>
			</td>
			<td onClick="showTask(<?=$row['task_id']?>)" >
				<div style="float:left"><?=$end_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_end_time']?></div>
			</td>
			<!--<td onClick="showTask(<$row['task_id']?>)" ><//$row['task_description']?></td>-->
		</tr>
		<?
	}
	?>
	<?php if ($canProcess):?>
		<tr>
			<th colspan="100%">
				<input type="button" value="Process" name="processReference" onClick="doProcess(this.form)"/>
			</th>
		</tr>
	<?php endif;?>
	<?
} else {
	showEmptyRow('1', 'second', 'Not found any references', '100%');
}

?>
</table>
</form>
<script>
	Calendar.enabled = true;

	Table("idReferenceList").setNormalHover(1);

	function showReference(id){
		location.href = "index.php?m=projects&a=view&project_id=" + id;
	}

	function doExport(frm) {
		frm.action = '?m=reports&a=do_r_account_receivable&suppressHeaders=1';
		frm.submit();
	}

	function doProcess(frm) {
		var elms = frm.elements['checkProcess[]'];
		var countChecked = 0;
		if (!isArray(elms)) {
			countChecked = elms.checked ? 1 : 0;
		} else {
			for(i = 0; i < elms.length; i++) {
				if (elms[i].checked) {
					countChecked++;
				}
			}
		}
		if (countChecked == 0) {
			alert("You should select one or more references to process!");
			return;
		}
		if (confirm("Do you want to process these references?")) {
			frm.elements['beingProcess'].value = 1;
			frm.submit();
		}
	}

	function showTask(id)
	{
		location.href = "index.php?m=tasks&a=view&task_id=" + id;
	}

	function checkAllCbProcess(frm, checked)
	{
		var elms = frm.elements['checkProcess[]'];
		if (!isArray(elms)) {
			elms.checked = checked;
			return;
		}
		for(i = 0; i < elms.length; i++) {
			elms[i].checked = checked;
		}
	}
</script>